<script setup lang="ts">
import { ref } from 'vue'
import { io } from 'socket.io-client'
import { Socket } from 'socket.io-client'
const message = ref('')
const remoteMedia: any = ref()
const videoMedia: any = ref()
const roomId = ref('fanjiantao')
const socket = io('localhost:3000')
socket.connect()
const userId = 'fanjiantao@' + Math.random().toString(16).slice(2)
const toUser = 'fanjiantao2@' + Math.random().toString(16).slice(2)

socket.on('connect', () => {
  socket.emit('join', roomId)
  socket.on('offer', (data) => {
    // offerSdp.value = JSON.stringify(data.offer)
    // createAnswer(socket)
    // console.log(data, 'fanjiantao2@offer')
  })
  socket.on('answer', (data) => {
    // console.log(data, 'fanjiantao@answer')
    // answerSdp.value = JSON.stringify(data.answer)
    // addAnswer()
  })

  socket.on('icecandidate', (data) => {})
})

const logger = (name, log) => {
  console.log('-----------' + name + '@satrt-----------')
  console.log(log)
  console.log('-----------' + name + '@end-----------')
  console.log('\n')
}

const sendDisplay = () => {
  getMedia()
}

const getMedia = () => {
  navigator.mediaDevices
    .getDisplayMedia({ audio: true, video: true })
    .then(function (stream: any) {
      // 将视频流赋值给video元素进行展示
      // videoUrl.value = stream
      videoMedia.value.srcObject = stream // console.log(pc1)
      // console.log(stream)
      // ;(pc1 as any).addStream(stream)

      stream.getTracks().forEach((track) => {
        pc1.addTrack(track, stream)
      })
      createOffer(socket)
    })
    .catch(function (error) {
      console.log('无法获取视频流', error)
    })
}

const pc1 = new RTCPeerConnection()
const pc2 = new RTCPeerConnection()

const createOffer = async (socket: Socket) => {
  const offer = await pc1.createOffer({
    offerToReceiveAudio: false,
    offerToReceiveVideo: false
  })

  logger('pc1-createOffer-success', offer.sdp)
  await pc1.setLocalDescription(offer)
  logger('pc1-setLocalDescription-success', '设置成功local')
  // pc1.onconnectionstatechange = (e) => {
  //   logger('pc1-connectionstatechange', e)
  // }
  pc1.onicecandidate = async (e) => {
    // logger('pc1-icecandidate', e.candidate?.candidate)
    if (e.candidate) {
      await pc2.addIceCandidate(e.candidate)
      logger('pc2.addIceCandidate-sucess', 'pc2 设置Candidate成功')
    }
  }
  //* 发送给pc2
  createAnswer(offer)
}

const createAnswer = async (desc) => {
  // pc2.oniceconnectionstatechange = (e) => {
  //   logger('pc2-iceconnectionstatechange', e)
  // }
  pc2.onicecandidate = async (e) => {
    // logger('pc2-icecandidate', e.candidate?.candidate)
    if (e.candidate) {
      await pc1.addIceCandidate(e.candidate)
      logger('pc1.addIceCandidate-sucess', 'pc1 设置Candidate成功')
    }
  }
  pc2.ontrack = (e) => {
    remoteMedia.value.srcObject = e.streams[0]
    logger('pc2.ontrack', e.streams[0])
  }
  await pc2.setRemoteDescription(desc)
  logger('pc2-setRemoteDescription-success', desc)

  const answer = await pc2.createAnswer()
  logger('pc2.createAnswer-success', answer)
  await pc2.setLocalDescription(answer)
  logger('pc2.setLocalDescription-success', '设置成功')
  await addAnswer(answer)
}

const addAnswer = async (answer) => {
  await pc1.setRemoteDescription(answer)
}
</script>

<template>
  <div>{{ message }}</div>
  <input type="text" v-model.trim="userId" />
  <input type="text" v-model.trim="toUser" />
  <button @click="sendDisplay">sendDisplay-发起共享数据</button>
  <div class="chat">
    <div class="userList">
      <ul>
        <li>用户1</li>
      </ul>
    </div>
    <div class="chat-message"></div>
    <div>LOCAL-VIDEO</div>
    <video style="width: 800px" autoplay ref="videoMedia" controls></video>
    <div>REMOTE-VIDEO</div>
    <video style="width: 800px" autoplay ref="remoteMedia" controls></video>
    <button @click="getMedia">获取视频流</button>
  </div>
</template>

<style lang="less">
@import './assets/css/styles.less';
</style>
